import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JedisDemoHash {
    public static void test1(Jedis jedis) {
        System.out.println("hset 和hget的使用");
        jedis.flushAll();
        jedis.hset("key", "f1", "1111");
        Map<String, String> fields = new HashMap<String, String>();
        fields.put("f1", "222");
        fields.put("f2", "333");
        jedis.hset("key", fields);
        System.out.println(jedis.hget("key", "f1"));
        Map<String, String> map = jedis.hgetAll("key");
        System.out.println("---------------");
        //顺便熟悉一下
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
    public static void test2(Jedis jedis) {
        System.out.println("hexists 的使用");
        jedis.flushAll();
        jedis.hset("key", "f1", "1111");
        jedis.hset("key", "f2", "2222");
        Boolean exists = jedis.hexists("key", "f1");
        System.out.println("exists:" + exists);
    }
    public static void test3(Jedis jedis) {
        System.out.println("hdel 的使用");
        jedis.flushAll();
        jedis.hset("key", "f1", "1111");
        jedis.hset("key", "f2", "2222");
        jedis.hdel("key", "f1");
        jedis.hdel("key","f2");
        System.out.println(jedis.hexists("key", "f1"));
        System.out.println(jedis.hexists("key", "f2"));
    }
    public static void test4(Jedis jedis) {
        System.out.println("hkeys 和hvals的使用");
        jedis.flushAll();
        jedis.hset("key", "f1", "1111");
        jedis.hset("key", "f2", "2222");
        Set<String> hkeys = jedis.hkeys("key");
        System.out.println(hkeys);
        List<String> hvals = jedis.hvals("key");
        System.out.println(hvals);
    }
    public static void test5(Jedis jedis) {
        System.out.println("hmset 和hmget的使用");
        jedis.flushAll();
        Map<String,String > map=new HashMap<>();
        map.put("f1", "1111");
        map.put("f2", "2222");
        map.put("f3", "3333");
        jedis.hmset("key", map);
        List<String> values = jedis.hmget("key","f1","f2","f3");
        System.out.println(values);
    }
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://localhost:8888");
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.auth("maihao1122");
            //test1(jedis);
            //test2(jedis);
            //test3(jedis);
            //test4(jedis);
            test5(jedis);
        }
    }
}
